<template>
  <el-col :span="24" class="comment bus-comment">
    <div class="add-ramark" @click.stop="showRemarkDiv(false)" v-show="commentStyle.showIcon && !isServiceBusiness">
      <i class="iconfont icon-beizhu"></i><span>{{$t('public.addRemarks')}}</span>
    </div>
    <el-tabs v-model="activeName" type="card" @tab-click="changeTab" v-show="commentStyle.showIcon && isServiceBusiness">
      <el-tab-pane :label="$t('business.commentIn')" name="in"></el-tab-pane>
      <el-tab-pane :label="$t('business.commentOut')" name="out"></el-tab-pane>
    </el-tabs>
    <div v-show="isshow">
      <main style="padding-top: 5px;">
        <div class="comment-input"
             ref="input"
             @blur="blur"
             contenteditable="'plaintext-only'"
             :placeholder="$t('business.pastePrompt')">
        </div>
        <b-file
          label=""
          :default="[]"
          :id="'attach'"
          ref="fields"
          @showBigImg="showBigImg"
          @blurEvent="cacheFields"
          :btnStyle="{type: 'primary', text: $t('business.attach'), size: 'mini'}">
        </b-file>
        <div ref="treeWrap" v-show="atShow" v-if="atShow !== null" class="at-tree" :style="pos">
          <!--<agent-tree ref="agentTree" @saveFollowedAgents="saveAtAgents" :showCheckbox="false"></agent-tree>-->
        </div>
        <div class="wrapper">
          <el-button @click.stop="cancel"  v-show="commentStyle.showIcon" class="primary_btn">{{$t('public.cancel')}}</el-button>
          <el-button type="primary" @click.stop="excuteBusinessComentAction" class="primary_btn">{{commentStyle.commitBtn}}</el-button>
        </div>
      </main>
    </div>
  </el-col>
</template>
<script>
  // import BTextarea from './base/Btextarea.vue'
  import BFile from './base/Bfile.vue'
  // import AgentTree from './agentTree'
  // import {getCurrentDateTime} from '@/utils/m7Utils'
  // import { position } from 'caret-pos'
  import {trim} from 'lodash'
  import { commitImgType2 } from '@/utils/publicMethod.js'
  // import * as types from '@/store/modules/business/mutation-types.js'
  export default {
    name: 'businessComment',
    props: {
      business: Object,
      isServiceBusiness: {type: Boolean, default: false},
      commentStyle: {
        type: Object,
        default: function () {
          return {
            commitBtn: this.$t('public.save'),
            showIcon: true
          }
        }
      }
    },
    components: {
      BFile
      // AgentTree
    },
    data () {
      return {
        activeName: '', // 为空或in是普通备注，out为服务工单外部备注
        form: {
          _id: this.business._id,
          backInfo: '',
          attach: []
          // atAgents: []
        },
        isshow: false,
        clear: '',
        pos: {
          left: '15px',
          top: '30px'
        },
        lastSelection: {},
        atShow: null // 默认值为null，不加载agentTree组件，当输入@后才加载
      }
    },
    watch: {
      business () {
        this.isshow = false
        this.activeName = ''
        this.form._id = this.business._id
      }
    },
    methods: {
      showBigImg (data) {
        // 获取所有包含imgA的图片
        let _array = this.$el.querySelectorAll('.bus-comment .imgA')
        commitImgType2(data, _array)
      },
      saveAtAgents ({_id, label}) {
        this.$refs.input.focus()
        this.atShow = false
        // 获取之前保留先来的信息。
        // 需要修改 keyIn 的代码，保存选区以及光标信息，用于获取在光标焦点离开前，光标的位置
        let selection = this.lastSelection.selection
        let range = this.lastSelection.range
        let textNode = range.startContainer
        // 删除 @ 符号。
        range.setStart(textNode, range.endOffset)
        range.setEnd(textNode, range.endOffset + 1)
        range.deleteContents()

        // 生成需要显示的内容，包括一个 span 和一个空格。
        let spanNode1 = document.createElement('span')
        let spanNode2 = document.createElement('span')
        spanNode1.className = 'at-text'
        spanNode1.id = _id
        spanNode1.setAttribute('contenteditable', false)
        spanNode1.innerHTML = '@' + label.split(' ')[0]
        spanNode2.innerHTML = '&nbsp;'
        this.form.atAgents.push(_id)
        // 将生成内容打包放在 Fragment 中，并获取生成内容的最后一个节点，也就是空格。
        let frag = document.createDocumentFragment()
        let node
        let lastNode
        frag.appendChild(spanNode1)
        while ((node = spanNode2.firstChild)) {
          lastNode = frag.appendChild(node)
        }
        // 将 Fragment 中的内容放入 range 中，并将光标放在空格之后。
        range.insertNode(frag)
        selection.extend(lastNode, 1)
        selection.collapseToEnd()
      },
      // keyIn (e) {
      //   let selection = window.getSelection()
      //   if (e.code === 'Digit2' && e.shiftKey) {
      //     // 输入@
      //     if (this.$refs.agentTree) {
      //       // 重置坐席树
      //       this.$refs.agentTree.resetAgent()
      //     }
      //     // debugger
      //     let {left, top} = position(this.$refs.input)
      //     // let offsetData = offset(this.$refs.input)
      //     // let windowWidth = document.documentElement.clientWidth
      //     let inputWidth = this.$refs.input.clientWidth
      //     if (this.$refs.treeWrap) {
      //       if (left + 33 > inputWidth) {
      //         // 光标在当前行的最后位置时
      //         this.pos.left = '15px'
      //         this.pos.top = top + 45 + 'px'
      //       } else if (left + 270 < inputWidth) {
      //         // 右侧没有超出window宽度时
      //         this.pos.left = left + 'px'
      //         this.pos.top = top + 25 + 'px'
      //       } else {
      //         // 右侧有超出window宽度时
      //         this.pos.left = inputWidth - 270 + 'px'
      //         this.pos.top = top + 25 + 'px'
      //       }
      //     }
      //     this.atShow = true
      //     // 保存光标信息
      //     this.lastSelection = {
      //       range: selection.getRangeAt(0),
      //       offset: selection.focusOffset,
      //       selection: selection
      //     }
      //   } else if (this.atShow) {
      //     this.atShow = false
      //   } else if (e.code === 'Backspace') {
      //     // 删除逻辑
      //     // 1 ：由于在创建时默认会在 @xxx 后添加一个空格，
      //     // 所以当得知光标位于 @xxx 之后的一个第一个字符后并按下删除按钮时，
      //     // 应该将光标前的 @xxx 给删除
      //     // 2 ：当光标位于 @xxx 中间时，按下删除按钮时应该将整个 @xxx 给删除。
      //     let range = selection.getRangeAt(0)
      //     var removeNode = null
      //     if (range.startOffset <= 1 && range.startContainer.nodeName === '#text' && range.startContainer.parentElement.className === 'comment-input') {
      //       removeNode = range.startContainer.previousElementSibling
      //     }
      //     if (range.startContainer.parentElement.className === 'at-text') {
      //       removeNode = range.startContainer.parentElement
      //     }
      //     if (removeNode) {
      //       let id = removeNode.id
      //       let index = this.form.atAgents.indexOf(id)
      //       if (index !== -1) {
      //         this.form.atAgents.splice(index, 1)
      //       }
      //       this.$refs.input.removeChild(removeNode)
      //     }
      //   }
      // },
      cancel () {
        this.isshow = false
        this.activeName = ''
      },
      // textarea失焦事件
      blur (e) {
        let src = e.target
        this.cacheFields({success: true, data: {backInfo: src.innerHTML}})
      },
      cacheFields (data) {
        let busCache = this.$getCache('busCache')
        let type = this.activeName === 'out' ? 'commentOut' : 'commentIn'
        let cacheId = this.business._id + type
        if (!busCache[cacheId]) busCache[cacheId] = {}
        Object.assign(busCache[cacheId], data.data)
      },
      pasteImg (evnet) {
        let ele = evnet.clipboardData.items || []
        for (let i = 0; i < ele.length; ++i) {
          if (ele.length === 1 && ele[i].kind === 'file' && ele[i].type.indexOf('image/') !== -1) {
            let blob = ele[i].getAsFile()
            let filename = 'clipboard' + new Date().getTime() + '.png'
            this.$refs.fields.addfile(blob, filename)
          }
        }
      },
      changeTab () {
        this.showRemarkDiv()
      },
      excuteBusinessComentAction () {
        let backInfo = trim(this.$refs.input.innerText)
        // this.form.atAgents = uniq(this.form.atAgents)
        this.form.backInfo = backInfo
        this.form.attach = (this.$refs.fields.submit()).data.attach || []
        this.$emit('event', {event: 'commentAction', data: {action: this.activeName, isService: this.isServiceBusiness, form: this.form}})
        // this.cancel()
      },
      showRemarkDiv (reset) {
        let busCache = this.$getCache('busCache')
        let type = this.activeName === 'out' ? 'commentOut' : 'commentIn'
        let cacheId = this.business._id + type
        this.isshow = true
        // 如果备注缓存存在进行赋值
        if (reset) {
          this.$refs.input.innerHTML = ''
          this.$refs.fields.resetForm([])
        } else {
          this.$refs.input.innerHTML = (busCache[cacheId] && busCache[cacheId].backInfo) || ''
          this.$refs.fields.resetForm(busCache[cacheId] && busCache[cacheId].attach)
        }
      }
    },
    mounted () {
      this.$nextTick(() => {
        // 绑定粘贴事件
        this.$refs.input.addEventListener('paste', this.pasteImg)
        this.$refs.input.setAttribute('contenteditable', 'plaintext-only')
      })
    },
    beforeDestroy () {
      this.$refs.input.removeEventListener('paste', this.pasteImg)
    },
    beforeMount () {
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../../assets/common.styl'
  .comment
    padding 20px 0 0
  header
    padding 10px 0
    text-align center
    h3
      display inline-block
      color $cf-gray1
  main
    position: relative
    .at-tree
      position absolute
      width:270px
      box-sizing border-box
      padding 10px
      border: 1px solid $c-border1
      z-index 6
      border-radius 3px
      background-color #fff
    .el-col
      margin-top 20px
    &:after
      content ''
      display block
      clear both
    .wrapper
      float right
      margin-top 5px
  .add-ramark
    cursor pointer
    display inline-block
    color $cf-gray1
    padding-bottom 5px
    .iconfont
      fontsize 20px
      margin-right 5px
      color $c-main
  .comment-input
    height 72px
    overflow-y scroll
    border 1px solid $c-border1
    padding 5px 15px
    border-radius 3px
    margin-bottom 10px
    &:empty
      &:before
        content attr(placeholder)
        color $cf-gray5
    &:focus
      content: none
  .at-text
    color $c-pink
</style>
